//
//  TCLYAddAddressViewController.m
//  YuErmuYing
//
//  Created by LYang on 16/8/29.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "TCLYAddAddressViewController.h"
#import "Macros.h"
#import "Masonry.h"
#import "TCLYMineModel.h"
#import "TCLYRegisterView.h"
#import "AddressPickView.h"
#import "TCLYUser.h"
@interface TCLYAddAddressViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextView *addAddressTextView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *telTextField;
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UIButton *defaultBtn;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (nonatomic, strong)TCLYMineModel * mineModel;
@property (nonatomic, strong)TCLYRegisterView * registerView;
@property(nonatomic,strong)NSDictionary *dictionary;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scorllviewLayout;
@property (nonatomic, strong) TCLYUser * user;

@end

@implementation TCLYAddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTitleView];
    //添加触碰手势(为了可以隐藏键盘)
    UITapGestureRecognizer * textFeildTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:textFeildTap];
    // Do any additional setup after loading the view from its nib.
    self.mineModel = [[TCLYMineModel alloc] init];
    self.registerView = [[TCLYRegisterView alloc] init];
    self.user = [[TCLYUser alloc] init];
    self.bgView.backgroundColor = bgColor;
    
    [self createView];
}
-(void)createView{
    self.addAddressTextView.editable = YES;
    self.addAddressTextView.font = [UIFont boldSystemFontOfSize:12];
    self.addAddressTextView.returnKeyType = UIReturnKeyDefault;//return键的类型
    self.addAddressTextView.keyboardType = UIKeyboardTypeDefault;//键盘类型
    self.addAddressTextView.textAlignment = NSTextAlignmentLeft; //文本显示的位置默认为居左
    self.addAddressTextView.dataDetectorTypes = UIDataDetectorTypeAll; //显示数据类型的连接模式（如电话号码、网址、地址等）
    self.addAddressTextView.textColor = [UIColor blackColor];
    self.addAddressTextView.text = @"详细地址";//设置显示的文本内容
    [self.defaultBtn setImage:[UIImage imageNamed:@"mineTic"] forState:UIControlStateNormal];
    [self.defaultBtn setImage:[UIImage imageNamed:@"mineTick-click"] forState:UIControlStateSelected];
    
    self.addressTextField.delegate = self;
    
    if (self.addAddressDic != nil) {
        self.nameTextField.text = self.addAddressDic[@"address_consignee"];
        self.telTextField.text = self.addAddressDic[@"address_consignee_pnone"];
        self.addressTextField.text = self.addAddressDic[@"address_add"];
        self.addAddressTextView.text = self.addAddressDic[@"address_detail"];
        if ([self.addAddressDic[@"address_default"] isEqual:@"1"]) {
            self.defaultBtn.selected = YES;
        }else{
            self.defaultBtn.selected = NO;
        }
        
    }
}
-(void)createTitleView{
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"收货地址";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(12, 22, 20, 20);
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    leftBtn.tag = 91;
    [leftBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    rightBtn.tag = 92;
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    rightBtn.frame = CGRectMake(screenWidth-12-20, 22, 30, 20);
    [rightBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)statusBtnAction:(id)sender{
    switch (((UIButton *)sender).tag) {
        case 91:{
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.navigationBarHidden = NO;
            self.tabBarController.tabBar.hidden = YES;
        }
            break;
        case 92:{
            if ([self.nameTextField.text isEqual:@""]) {
                [self.registerView prompt:@"收货人不能为空哦！" Controller:self];
                return;
            }
            if ([self.telTextField.text isEqual:@""]) {
                [self.registerView prompt:@"电话号码不能为空哦！" Controller:self];
                return;
            }
            if ([self.addressTextField.text isEqual:@""]) {
                [self.registerView prompt:@"地区不能为空哦！" Controller:self];
                return;
            }
            if ([self.addAddressTextView.text isEqual:@"详细地址"]) {
                [self.registerView prompt:@"请填写详细地址" Controller:self];
                return;
            }
            if (self.addAddressDic == nil) {
                NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid",self.nameTextField.text,@"consignee",self.telTextField.text, @"phone",self.addressTextField.text, @"add",self.addAddressTextView.text, @"detail", nil];
                [self.mineModel addAddressParameter:dic];
                
            }else if (self.addAddressDic != nil){
             
                NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid",self.nameTextField.text,@"consignee", self.telTextField.text, @"phone", self.addressTextField.text, @"add",self.addAddressTextView.text, @"detail",self.addAddressDic[@"address_id"], @"aid", nil];
                [self.mineModel updateAddressParameter:dic];
            }
        }
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//隐藏键盘的方法
-(void)dismissKeyboard{
    for (int j = 0; j<4; j++) {
        UITextField * textField = [self.view viewWithTag:501+j];
        [textField resignFirstResponder];
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField isEqual:self.addressTextField]) {
        [self.view endEditing:YES];
        
        AddressPickView *addressPickView = [AddressPickView shareInstance];
        [self.view addSubview:addressPickView];
        addressPickView.block = ^(NSString *province,NSString *city,NSString *town){
            
            
            
            self.addressTextField.text = [NSString stringWithFormat:@"%@%@%@",province,city,town];
            
//            for (NSString *str in self.dictionary) {
            
//                if([str rangeOfString:city].location != NSNotFound)
//                {
//                    
//                    邮编.text = self.dictionary[str];
//                }
//            }
        };
    }
}
//懒加载
-(NSDictionary *)dictionary{
    
    if(!_dictionary){
        
        //获取邮编 citys.plist
        NSString *path=[[NSBundle mainBundle]pathForResource:@"citys.plist" ofType:nil];
        _dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    return _dictionary;
}

-(IBAction)defaultBtn:(id)sender{
    self.defaultBtn.selected = !self.defaultBtn.selected;
    if (self.defaultBtn.selected == YES) {
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid", self.dictionary[@"address_id"], @"aid", nil];
        [self.mineModel defaultAddressParameter:dic];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
